package com.ruangong.GitClient.GiteeAPI;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.ruangong.GitClient.GitConfig;
import okhttp3.*;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

public class GiteeUser {
    public static OkHttpClient client = new OkHttpClient();
    public static String accessToken;
    public static String refreshToken;

    public GiteeUser() {

    }

    public GiteeUser(String accessToken , String refreshToken) {
        GiteeUser.accessToken = accessToken;
        GiteeUser.refreshToken = refreshToken;
    }

    /**
     * 获取
     * @return refreshToken
     */
    public static String getRefreshToken() {
        return refreshToken;
    }

    /**
     * 设置
     * @param refreshToken
     */
    public static void setRefreshToken(String refreshToken) {
        GiteeUser.refreshToken = refreshToken;
    }

    public static String getAccessToken() {
        return accessToken;
    }

    public void setToken(String AccessToken) {
        GiteeUser.accessToken = AccessToken;
    }

    /**
     * 显示用户信息。
     */
    public void showInfo() {
        System.out.println("Token: " + accessToken);
    }

    /**
     * 获取用户的所有存储库。
     * @return 用户的所有存储库
     */

    public List<GiteeRepository> getRepositories() {
        System.out.println("Getting repositories...");
        String url = "https://gitee.com/api/v5/user/repos?access_token="+accessToken+"&type=all&sort=full_name&page=1&per_page=20";

        try (Response response = client.newCall(new Request.Builder().url(url).build()).execute()){
            if(response.isSuccessful()){
                assert response.body() != null;
                String jsonResponse = response.body().string();
                System.out.println(jsonResponse);
                Gson gson = new Gson();
                Type listType = new TypeToken<List<GiteeRepository>>(){}.getType();
                return gson.fromJson(jsonResponse, listType);
            } else {
                System.err.println("Failed to fetch repositories: " + response.message());
            }
        } catch (IOException e) {
            System.err.println("Error making HTTP request: " + e.getMessage());

        }
        return null;
    }


    /**
     * 刷新访问令牌。
     * @return 如果成功刷新访问令牌，则返回true；否则返回false。
     * @throws IOException 如果发生I/O错误，则抛出此异常。
     */
    public static boolean refreshToken() throws IOException {
        if (GiteeUser.refreshToken != null) {
        RequestBody body = new FormBody.Builder()
                .add("grant_type", "refresh_token")
                .add("refresh_token", GiteeUser.refreshToken)
                .add("client_id", GitConfig.GITEE_CLIENT_ID)
                .add("client_secret", GitConfig.GITEE_CLIENT_SECRET)
                .build();

        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token")
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 假设服务器返回的是 JSON 格式的响应体
            assert response.body() != null;
            String jsonResponse = response.body().string();
            // 解析 JSON 响应以获取新的访问令牌
            GiteeUserFromJson(jsonResponse);
            System.out.println("New access token: " + GiteeUser.accessToken);
            System.out.println("New refresh token: " + GiteeUser.refreshToken);
            return true;
        }
        } else {
            System.out.println("refreshToken is null. Unable to refresh token.");
        }
        return false;
    }

    public static void GiteeUserFromJson(String json) {
        JsonElement jsonObject = JsonParser.parseString(json);
        GiteeUser.accessToken = jsonObject.getAsJsonObject().get("access_token").getAsString();
        GiteeUser.refreshToken = jsonObject.getAsJsonObject().get("refresh_token").getAsString();
    }


    public static void main(String[] args) {
        //每次运行完要更新Token值
        GiteeUser giteeUser = new GiteeUser("3fe2eef8439aaf0bcb13566a026e0edd","4079928ff5a5c846ac47a2e73b8f0c3acf24d434c6a28b7a958bf77c04ebf8e5");
        //{"access_token":"3d665ceac30463da6b86066ea1fb9172","token_type":"bearer","expires_in":86400,"refresh_token":"738caae975f9255ae2cfb935446ed3b1e9ae5ef5aa9b6e175f210149ab058d6f","scope":"user_info projects pull_requests issues notes keys hook groups gists enterprises emails","created_at":1715421032}
        System.out.println(giteeUser.getAccessToken());

        String accessToken = giteeUser.getAccessToken();
        if (accessToken != null) {
        List<GiteeRepository> repos = giteeUser.getRepositories();
        //TODO：显示所有存储库的信息，这里的函数可以获取到该账号的所有存储库
        for (GiteeRepository repo : repos) {
//            System.out.println("Repository Human_Name: " + repo.getHuman_name());
//            System.out.println("Repository Content: " + repo.getName());
//            System.out.println("Description: " + repo.getDescription());
//            System.out.println(repo);
            repo.showRepositoryInfo();
        }
        try {
            boolean flag = giteeUser.refreshToken();
//            System.out.println("New access token: " + newAccessToken);
            System.out.println("Refresh token success: " + flag);
        }
        catch (Exception e) {
            System.err.println("Error refreshing token: " + e.getMessage());
        }
        } else {
            System.err.println("Failed to obtain access token.");
        }
    }

    public String toString() {
        return "GiteeUser{client = " + client + ", accessToken = " + accessToken + ", refreshToken = " + refreshToken + "}";
    }
}
